<template>
  <div style="max-width: 512px !important;">
    <van-nav-bar title="收货地址" left-arrow @click-left="onClickLeft" />
    <van-address-list v-model="chosenAddressId" :list="list" :disabled-list="disabledList" disabled-text="暂无收获地址,请添加地址"
      default-tag-text="默认" @add="onAdd" @edit="onEdit" @select="select"
      v-show="disabledList.length == 0 && list.length == 0" />
    <van-address-list v-model="chosenAddressId" :list="list" :disabled-list="disabledList" disabled-text="以下地址超出配送范围"
      default-tag-text="默认" @add="onAdd" class="button" @edit="onEdit"
      v-show="disabledList.length > 0 || list.length > 0" @select="select" />
  </div>


</template>

<script setup>
import { ref, onMounted } from 'vue';
import { showToast } from 'vant';
import { useRouter } from 'vue-router';
import { POST } from "../services/request";
const router = useRouter();

// 获取用户信息
const userData = JSON.parse(localStorage.getItem('LoginUser'));
// 获取用户id
const uid = userData.id;
// 获取用户手机号
const mobile = userData.mobile
// console.log(mobile);



const chosenAddressId = ref(null);
// 存放可配送地址
const list = ref([]);
// 存放超出配送区域的地址
const disabledList = [];

onMounted(async () => {
  await getAddressList();
  // console.log(chosenAddressId.value);
})

// 获取地址列表
const getAddressList = async () => {
  const getAddressRes = await POST({
    url: '/Address/getAddress',
    params: {
      uid: uid,
      mobile: mobile
    }
  })
  if (getAddressRes.code === 1) {
    list.value = getAddressRes.data;
    list.value.forEach(item => {
      if (item.isDefault == 1) {
        chosenAddressId.value = item.id
        localStorage.setItem('currAddress',JSON.stringify(item));
        // console.log(chosenAddressId.value);
      }
    })
  }
}

// 新增地址
const onAdd = async () => router.push('addressAdd');

// 当前选择
const select = (item) => {
  // console.log(item);
  localStorage.removeItem('currAddress');
  chosenAddressId.value = item.id
  localStorage.setItem('currAddress',JSON.stringify(item));
  // console.log(chosenAddressId.value);
  // history.back();
  
}

// 编辑地址
const onEdit = (item) => {
  // showToast('编辑地址:' + item.id);
  router.push({
    path: '/addressEdit',
    query: {
      id: item.id
    }
  });
}

// 返回
const onClickLeft = () => history.back();


</script>

<style scoped></style>